# -*- coding: utf-8 -*-

# callbacks.py

import time
import requests
import json
def callback_request_post(ch, methods, properties, body, callback_logger):
    message = body.decode('utf-8')
    callback_logger.info(f"Processing callback_type_a with message: {message}")
    
    try:
        # 解析消息内容
        data = json.loads(message)
        
        # 获取请求信息
        url = data.get('url')
        method = data.get('method', 'GET')
        headers = data.get('headers', {})
        payload = data.get('payload', {})
        
        # 发送请求
        if method.upper() == 'GET':
            response = requests.get(url, headers=headers, params=payload)
        elif method.upper() == 'POST':
            #超时时间设为5分钟
            response = requests.post(url, headers=headers, data=payload, timeout=300)
        elif method.upper() == 'PUT':
            response = requests.put(url, headers=headers, data=payload)
        elif method.upper() == 'DELETE':
            response = requests.delete(url, headers=headers, data=payload)
        elif method.upper() == 'PATCH':
            response = requests.patch(url, headers=headers, data=payload)
        elif method.upper() == 'JSON':
            # 超时时间设为5分钟
            # 注意：如果请求体为json格式，则需要设置json参数
            
            response = requests.post(url, headers=headers, json=payload)
        else:
            raise ValueError(f"不支持的请求方法: {method}")
        
        # 检查响应
        response.raise_for_status()
        
        # 记录响应
        callback_logger.info(f"请求成功: {url}, 状态码: {response.status_code}")
        callback_logger.debug(f"响应内容: {response.text}")
        
        # 手动确认消息
        ch.basic_ack(delivery_tag=methods.delivery_tag)
    except requests.RequestException as e:
        callback_logger.error(f"请求失败: {str(e)}")
        # 将消息发送到死信队列
        ch.basic_nack(delivery_tag=methods.delivery_tag, requeue=False)
    except json.JSONDecodeError:
        callback_logger.error("无效的JSON消息格式")
        # 将消息发送到死信队列
        ch.basic_nack(delivery_tag=methods.delivery_tag, requeue=False)
    except Exception as e:
        callback_logger.error(f"处理请求时发生错误: {str(e)}")
        # 将消息发送到死信队列
        ch.basic_nack(delivery_tag=methods.delivery_tag, requeue=False)